<template>
  <div class="page-mobile-course">
    <white-header :isShowTopNav="true" :isShowBack="true" :isShowRight="true" :title="title || this.getMajorName(major_id)"></white-header>
    <div class="tap-content" v-if="action != 'live' && !major_id">
      <div
        :class="['tap', item.is_actived ? 'active' : null]"
        v-for="(item, index) in major_rec_list"
        :key="index"
        @click="handleClickTap(item)"
      >{{item.name}}</div>
    </div>
    <div class="course_list">
      <course-card
        v-for="(item, index) in course_list"
        :detail="item"
        :is_member="is_member"
        :user_member="user_member"
        :memberDiscount="memberDiscount"
        :key="index"
         :bottomInline="index != (course_list.length - 1)"
      ></course-card>
      <div class="no-more" v-if="course_list.length != 0">{{ $t("locale.mobile.course.t1") }}</div>
      <van-empty :description="$t('locale.mobile.course.t2')" v-if="course_list.length == 0" />
    </div>
  </div>
</template>

<script>
import CourseCard from "~/components/mobile/CourseCard.vue";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { getCourse, getCourseByMajor,getMajorTreeCourse } from "~/api/course";
import { getMajorList } from "~/api/major";
import { getMemberInfo, getMember } from "~/api/member";
import { mapState, mapActions, mapMutations } from "vuex";
export default {
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    CourseCard,
    WhiteHeader,
  },
  data() {
    return {
      page: 1,
      pageSize: 6,
      total: 0,
      course_list: [],
      scroll_heigth: 0,
      memberDiscount: {},
      major_rec_list: [], //推荐专业
      action:"",
      major_id:"",
      title:"",
    };
  },
  computed: {
    ...mapState({
      token(state) {
        return state.token;
      },
      user_info(state) {
        return state.user_info;
      },
      major_list(state) {
        return [
          {
            text: this.$t("locale.mobile.course.t3"),
            value: "",
          },
          ...state.major_list.map((i) => {
            return {
              ...i,
              value: i.id,
              text: i.name,
            };
          }),
        ];
      },
      class_list(state) {
        return state.class_list;
      },
      is_loading(state) {
        return state.is_loading;
      },
      is_member(state) {
        return JSON.stringify(state.member_info) != "{}";
      },
      user_member(state) {
        return state.member_info;
      },
    }),
  },
  watch: {},
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    ...mapActions(["initMajorList", "initClassList", "initMember"]),
    async getMajorData() {
      this.SET_IS_LOADING(true);
      let params = {
        offset: 0,
        limit: 10,
        sort: "videoSort desc",
        isRec: 1,
      };
      let result = await getMajorList(params);
      if (result && result.data && result.data.code == 200) {
        this.SET_IS_LOADING(false);
        this.major_rec_list = [
          {
            name: this.$t("locale.mobile.index.t8"),
            id: "all",
            is_actived: true,
          },
          ...result.data.data.rows
            .filter((i) => i.isRec == 1)
            .map((i, x) => {
              return { ...i, is_actived: false };
            }),
        ];
      } else {
        this.SET_IS_LOADING(false);
        this.$toast(
          this.$t("locale.mobile.index.t9") + result &&
            result.data &&
            result.data.msg
        );
      }
    },
    async handleClickTap(item) {
      if (item.id == this.major_rec_list.filter((i) => i.is_actived)[0]) {
        return false;
      }
      this.major_rec_list = this.major_rec_list.map((i) => {
        if (i.id == item.id) {
          return {
            ...i,
            is_actived: true,
          };
        } else {
          return {
            ...i,
            is_actived: false,
          };
        }
      });
      this.page = 1;
      if (item.id == "all") {
        this.getData();
        // this.getData();
      } else {
        this.getData({
            majorId: item.id,
          })
        // this.getData({
        //   majorId: item.id
        // });
      }
    },
    async getMemberInfo() {
      this.SET_IS_LOADING(true);
      if (this.token && Object.keys(this.user_info).length > 0) {
        let memberDiscount = await getMemberInfo(this.user_info.id);
        if (
          memberDiscount &&
          memberDiscount.data &&
          memberDiscount.data.code == 200
        ) {
          this.memberDiscount = memberDiscount.data.data;
        } else {
          
        }
      }

      this.SET_IS_LOADING(false);
    },
    async getData(other_params,fetch_type) {
      return new Promise(async (resolve, reject) => {
        this.SET_IS_LOADING(true);
        let params = {};
        if(this.action === 'rec'){
          params = {
            offset: this.pageSize * (this.page - 1),
            limit: this.pageSize,
            sort: "sortIndex desc",
            isRec: 1,
            ...other_params,
          };
        }else if(this.action === 'free'){
          params = {
            offset: this.pageSize * (this.page - 1),
            limit: this.pageSize,
            sort: "sortIndex desc",
            isFree: 1,
            ...other_params,
          };
        }else if(this.action === 'live'){
          params = {
            offset: this.pageSize * (this.page - 1),
            limit: this.pageSize,
            sort: "sortIndex desc",
            isLive: 1,
            ...other_params,
          };
        }else{
          console.log("专业课程");
          params = {
            offset: this.pageSize * (this.page - 1),
            limit: this.pageSize,
            sort: "sortIndex desc",
            ...other_params,
          };
        }
        // let params = {
        //   offset: this.pageSize * (this.page - 1),
        //   limit: this.pageSize,
        //   sort: "sortIndex desc",
        //   isRec: 1,
        //   ...other_params,
        // };
        let result = {};
        if(other_params && other_params.majorId){
          result = await getMajorTreeCourse(params);
        }else{
          result = await getCourseByMajor(params);
        }
        // let result = await getCourseByMajor(params);
        if (result && result.data && result.data.code == 200) {
          this.SET_IS_LOADING(false);
          this.total = result.data.data.total;
          let courseArr = [];
          if (fetch_type == "pullup") {
            courseArr = [...this.course_list,...result.data.data.rows];
          }else{
            courseArr = result.data.data.rows;
          }
          this.course_list = courseArr.map(item=>{
            let currentTime = new Date().getTime();
            if(!(item.isDiscount == 1 && currentTime >= item.discountStartTime && item.discountEndTime >= currentTime)){
              return {
                ...item,
                isDiscount:0
              };
            }else{
              return item;
            }
          });
          
        } else {
          this.SET_IS_LOADING(false);
          this.$toast(
            this.$t("locale.mobile.index.t9"),
            result && result.data && result.data.msg
          );
        }
      })
        .then()
        .catch((e) => {
          this.SET_IS_LOADING(false);
        });
    },
    getMajorName(id) {
      let res = this.major_list.filter((i) => i.id == id);
      if (res.length > 0) {
        return res[0].name;
      } else {
        return "";
      }
    },
    initPage() {
      return new Promise((res, rej) => {
        if (process.client) {
          try {
            // console.log(this.$route.query.action)
            this.action = this.$route.query.action;
            this.major_id = this.$route.query.major_id;
            if(this.action){
              if(this.action == 'rec'){
                this.title = "推荐课程";
              }else if(this.action == 'free'){
                this.title = "免费课程";
              }else if(this.action == 'live'){
                this.title = "直播课程";
              }
              this.getData();
            }else{
              this.getData({
                majorId: this.major_id,
              })
            }
            
            
            this.initMajorList();
            this.getMajorData();
            this.getMemberInfo();
            this.initMember();
            res("success");
          } catch (e) {
            console.log(e);
            rej(e);
          }
        }
      }).then();
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function () {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      if (scrollTop + clientHeight >= scrollHeight - 120) {
        console.log("上拉加载");
        if (this.total <= this.course_list.length) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.page++;
        if(this.major_id){
          this.getData({
                majorId: this.major_id,
              },"pullup");
        }else{
          this.getData({},"pullup");
        }
        
      }
    },
    eventListener() {
      this.throttle(this.pullUp, 30);
    },
    initState() {
      this.page = 1;
      this.pageSize = 10;
      this.total = 0;
    },
  },
  activated() {
    if (process.client) {
      this.$nextTick(() => {
        setTimeout(() => {
          document.body.scrollTop = this.scroll_heigth;
          document.documentElement.scrollTop = this.scroll_heigth;
        }, 0);
      });
      window.addEventListener("scroll", this.eventListener);
      this.initPage()

    }
    this.setDisabled(false);
    this.refreshFun(() => {
      this.initPage()
        .then((res) => {
          if (res == "success") {
            this.setLoading(false);
          }
        })
        .catch(() => {
          this.setLoading(false);
          this.SET_IS_LOADING(false);
        });
    });
  },
  deactivated() {
    let scroll_heigth =
      document.documentElement.scrollTop || document.body.scrollTop;
    this.scroll_heigth = scroll_heigth;
    this.initState();
    this.setDisabled(true);
    window.removeEventListener("scroll", this.eventListener);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.eventListener);
  },
  created() {
    //开启下拉刷新
    this.setDisabled(false);
    //初始化页面数据
    this.initPage();
    //下拉回调
    this.refreshFun(() => {
      this.initPage()
        .then((res) => {
          if (res == "success") {
            this.setLoading(false);
          }
        })
        .catch(() => {
          this.setLoading(false);
          this.SET_IS_LOADING(false);
        });
    });
    //返回上次页面滚动条的位置
    // this.$nextTick(() => {
    //   document.body.scrollTop = this.scroll_heigth;
    //   document.documentElement.scrollTop = this.scroll_heigth;
    // });
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  },
};
</script>

<style lang="scss" scoped>
.page-mobile-course {
  min-height: calc(100vh - 1.6rem);
  .course_list {
    // padding: 0.16rem 0.16rem;
    .no-more {
      padding: 0.2rem 0 0;
      text-align: center;
      font-size: 0.26rem;
      color: #666;
    }
  }
  .tap-content {
    width: 100%;
    overflow-x: scroll;
    overflow-y: hidden;
    -webkit-backface-visibility: hidden;
    -webkit-perspective: 1000;
    -webkit-overflow-scrolling: touch;
    text-align: justify;
    box-sizing: border-box;
    display: flex;
    // margin-top: .2rem;
    border-top: 1px solid #ededf1;
    border-bottom: 1px solid #ededf1;
    &::-webkit-scrollbar {
      display: none;
    }
    .tap {
      text-align: center;
      flex-shrink: 0;
      width: 30%;
      font-size: .2688rem;
      height: 0.8rem;
      line-height: 0.8rem;
      position: relative;
      color: #979899;
    }
    .tap.active::before {
      content: "";
      display: block;
      position: absolute;
      width: 0.6rem;
      height: 0.04rem;
      background: var(--theme-color);
      left: 50%;
      bottom: 0;
      transform: translateX(-50%);
    }
    .tap.active{
      font-weight: bold;
      color: #313233;
    }
  }
  .select-action {
    height: 0.8rem;
    .select-menu {
      position: fixed;
      top: 0.8rem;
      left: 0;
      width: 100%;
      z-index: 9;
    }
  }
}
</style>
<style lang="scss">
.page-mobile-course {
  
  .van-popup {
    width: 7.2rem;
  }
}
</style>
